// 政采云电子发票核心模型
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DECIMAL, VIRTUAL } = app.Sequelize;

  return app.model.define('invoice', {
    order_id: { // 政采云订单号
      type: STRING(32),
      allowNull: false,
      comment: '政采云订单号'
    },
    province_code: { // 省份行政区划代码
      type: STRING(6),
      allowNull: false,
      comment: '省份代码'
    },
    status: { // 工单状态
      type: INTEGER,
      defaultValue: 0,
      comment: '0-待审核 1-已通过 2-已开票 3-已驳回'
    },
    invoice_amount: { // 开票金额
      type: DECIMAL(12, 2),
      allowNull: false,
      comment: '含税金额'
    },
    tax_control_code: { // 税控设备编号
      type: STRING(64),
      comment: '金税盘编号'
    }
  }, {
    paranoid: true, // 启用软删除
    indexes: [
      { fields: ['province_code'] },
      { fields: ['status', 'created_at'] }
    ],
    hooks: {
      afterUpdate: async (invoice, options) => {
        app.redis.publish('invoice_status_change', 
          JSON.stringify(invoice));
      }
    }
  });
};